package com.fary.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;

public class GroupChatClient {

    /**
     * 服务器IP地址
     */
    private static final String SERVER_HOST = "127.0.0.1";

    /**
     * 服务器端口号
     */
    private static final int SERVER_PORT = 6667;

    /**
     * 对应的Selector
     */
    private Selector selector;

    /**
     * 客户端的Channel
     */
    private SocketChannel socketChannel;

    /**
     * 不知道干啥
     */
    private String userName;

    /**
     * 重写构造方法
     */
    public GroupChatClient () {
        try {
            selector = Selector.open();
            // 1. 连接到服务器
            socketChannel = SocketChannel.open(new InetSocketAddress(SERVER_HOST, SERVER_PORT));
            // 2. 设置阻塞状态
            socketChannel.configureBlocking(false);
            // 3. 将Channel注册到Selector中
            socketChannel.register(selector, SelectionKey.OP_READ);
            // 4. 获取客户端名称，并且打印客户端信息
            userName = socketChannel.getLocalAddress().toString();
            System.out.println(userName + " is ok!!!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * Main方法
     *
     * @param args
     */
    public static void main(String[] args) {
        GroupChatClient groupChatClient = new GroupChatClient();
        // 启动一个线程用户处理服务器的消息
        new Thread(()->{
           while (true) {
               groupChatClient.readMessageFromServer();
               try {
                   Thread.sleep(3000);
               } catch (InterruptedException e) {
                   e.printStackTrace();
               }
           }
        }).start();

        // 主线程用于发送数据给服务器端
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextLine()) {
            String s = scanner.nextLine();
            groupChatClient.sendMessage(s);
        }
    }

    /**
     * 给服务器发送消息
     *
     * @param message           消息内容
     */
    public void sendMessage (String message) {
        message = userName + " say: " + message;
        try {
            socketChannel.write(ByteBuffer.wrap(message.getBytes()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 读取从服务器端回复的消息
     *
     */
    public void readMessageFromServer () {
        // 1. 获取对应的Channel
        try {
            int readChannelCount = selector.select();
            if (readChannelCount == 0 ) {
                System.out.println("There is no message from server .");
                return;
            }
            if (readChannelCount > 0) {
                // 2. 获取所有的key，并且开始遍历所有的key
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator<SelectionKey> keyIterator = selectionKeys.iterator();
                while (keyIterator.hasNext()) {
                    SelectionKey key = keyIterator.next();
                    // 判断key是否是可读的
                    if (key.isReadable()) {
                        // 通过key获取对应的Channel
                        SocketChannel channel = (SocketChannel) key.channel();
                        // 分配一个缓冲区
                        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                        // 并且读取数据到缓冲区中
                        channel.read(byteBuffer);
                        // 把缓冲区数据转化为字符串
                        String message = new String(byteBuffer.array());
                        System.out.println("Message read from server, message: " + message);
                    }
                    keyIterator.remove();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
